﻿using AutoMapper;

namespace ZeroSum.Extend.Mapper.Extensions;

public static class MapperExtensions
{
    private static IMapper? _mapper;

    public static void SetMapper(IMapper? mapper)
    {
        _mapper = mapper;
    }

    /// <summary>
    ///     将对象映射为指定类型
    /// </summary>
    /// <typeparam name="TTarget">要映射的目标类型</typeparam>
    /// <param name="source">源对象</param>
    /// <returns>目标类型的对象</returns>
    public static TTarget MapTo<TTarget>(this object? source)
    {
        CheckMapper();
        return _mapper!.Map<TTarget>(source);
    }

    /// <summary>
    ///     使用源类型的对象更新目标类型的对象
    /// </summary>
    /// <typeparam name="TSource">源类型</typeparam>
    /// <typeparam name="TTarget">目标类型</typeparam>
    /// <param name="source">源对象</param>
    /// <param name="target">待更新的目标对象</param>
    /// <returns>更新后的目标类型对象</returns>
    public static TTarget MapTo<TSource, TTarget>(this TSource source, TTarget target)
    {
        CheckMapper();
        return _mapper!.Map(source, target);
    }

    /// <summary>
    ///     集合映射
    /// </summary>
    /// <param name="source">元数据</param>
    /// <typeparam name="TSource">源类型</typeparam>
    /// <typeparam name="TTarget">目标类型</typeparam>
    /// <returns>目标类型对象集合</returns>
    public static IList<TTarget> MapList<TSource, TTarget>(this IList<TSource> source)
    {
        CheckMapper();
        return _mapper!.Map<IList<TSource>, IList<TTarget>>(source);
    }

    /// <summary>
    ///     检测mapper是否被注入
    /// </summary>
    /// <exception cref="InvalidDataException"></exception>
    private static void CheckMapper()
    {
        if (_mapper == null)
            throw Exceptions.InvalidDataException.Of("IMapper为空，请调用UseAutoMapper");
    }
}